package indi.jp.project.base.controller;

import indi.jp.project.base.entity.Department;
import indi.jp.project.base.service.DepartmentService;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.util.SimpleEntityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bas/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @GetMapping("/queryGrid")
    @ResponseBody
    public JsonResult queryGrid(@ModelAttribute Department entity, HttpServletRequest request){
        SimpleEntityUtil<Department> simpleEntityUtil = new SimpleEntityUtil<>();
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            Map<String, Object> map = departmentService.queryGrid(entity);
            return JsonResult.success(map);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(@RequestBody Department entity, HttpServletRequest request) {
        SimpleEntityUtil<Department> simpleEntityUtil = new SimpleEntityUtil<>();
        entity = simpleEntityUtil.setBaseEntity(entity, request);
        try {
            int effectRow = departmentService.save(entity);
            if(effectRow > 0){
                return JsonResult.success("");
            } else {
                return JsonResult.failure("保存失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @PostMapping("/deleteByCode")
    @ResponseBody
    public JsonResult deleteByCode(HttpServletRequest request) {
        String code = request.getParameter("code");
        try {
            int effectRow = departmentService.deleteByCode(code);
            if(effectRow > 0){
                return JsonResult.success("");
            } else {
                return JsonResult.failure("未能成功删除，请刷新查看数据是否存在");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

    @GetMapping("/queryTreeList")
    @ResponseBody
    public JsonResult queryTreeList(@ModelAttribute Department entity){
        try {
            List<Department> list = departmentService.queryTreeList(entity);
            return JsonResult.success(list);
        } catch (SQLException e) {
            e.printStackTrace();
            return JsonResult.error();
        }
    }

}
